//
// Created by root on 6/24/17.
//

#include <stdio.h>
#include <memory.h>
#include "runner_base.h"
#include "../../src/base/utils.h"

static void test_match_regex() {
    assert_true(match_regex("[a-zA-Z]", "a"));
    assert_true(match_regex("[a-zA-Z]", "Z"));
}

static void test_match_regex_groups() {
    char **strings = match_regex_groups("([0-9]+.[0-9]*e[0-9]+)-([0-9]*)/([0-9]*)i", 4, "3.1e2-5/6i");
    assert_string_equal(*strings, "3.1e2-5/6i");
    assert_string_equal(*(strings + 1), "3.1e2");
    assert_string_equal(*(strings + 2), "5");
    assert_string_equal(*(strings + 3), "6");
    assert_null(*(strings + 4));
}

static void test_concatenate() {
    char *string = strdup("");
    string = concatenate(string, "aaa");
    assert_string_equal(string, "aaa");
    string = concatenate(string, NULL);
    assert_string_equal(string, "aaa");
    string = concatenate(string, "");
    assert_string_equal(string, "aaa");
    string = concatenate(string, "bbb");
    assert_string_equal(string, "aaabbb");
}

//todo other utils

#define REPETITION_TEXT  "abbbcddeee"

static void test_repetitions() {
    FILE* fp = create_temp_file(REPETITION_TEXT);
    int count = repetitions(fp, 'd');
    assert_int_equal(count, 0);
    count = repetitions(fp, 'a');
    assert_int_equal(count, 1);
    count = repetitions(fp, 'b');
    assert_int_equal(count, 3);
    count = repetitions(fp, 'c');
    assert_int_equal(count, 1);
    count = repetitions(fp, 'd');
    assert_int_equal(count, 2);
    count = repetitions(fp, 'e');
    assert_int_equal(count, 3);
    count = repetitions(fp, 'e');
    assert_int_equal(count, 0);
}

static int condition1(int c) {
    return c != 'c' && c != 'f';
}

static void test_read_until() {
    FILE* fp = create_temp_file(REPETITION_TEXT);
    char* code = read_until(fp, condition1);
    printf("%s\n", code);
    int count = repetitions(fp, 'c');
    assert_int_equal(count, 1);
    code = read_until(fp, condition1);
    printf("%s\n", code);
}

int main(int argc, char **argv) {
    const struct CMUnitTest tests[] = {
            cmocka_unit_test(test_match_regex),
            cmocka_unit_test(test_match_regex_groups),
            cmocka_unit_test(test_concatenate),
            cmocka_unit_test(test_repetitions),
            cmocka_unit_test(test_read_until),
    };
    return cmocka_run_group_tests(tests, setup_base, teardown_base);
}

